/*
 * @Author      : ZhouQiJun
 * @Date        : 2025-08-11 16:23:25
 * @LastEditors : ZhouQiJun
 * @LastEditTime: 2025-08-12 10:50:36
 * @Description : 关于博主，前端程序员，最近专注于 webGIS 开发
 * @加微信         : MasonChou123，进技术交流群
 */
import OlExtMask from 'ol-ext/filter/Mask'

import { WKT } from 'ol/format'
import { Fill } from 'ol/style'

export default function createMask(wkt) {
  const feat = new WKT().readFeature(wkt, {
    dataProjection: 'EPSG:4326',
    featureProjection: 'EPSG:4326',
    //featureProjection: 'EPSG:3857',
  })
  const mask = new OlExtMask({
    feature: feat,
    fill: new Fill({ color: [60, 151, 255, 0.3] }), // #112949
  })
  return { mask, feat }
}

/**
 * 将 CSS 十六进制颜色转换为 ol 可用的 [r,g,b,a] 或 'rgba(...)' 字符串
 * 支持 #RGB, #RRGGBB, #RGBA, #RRGGBBAA
 * @param {string} hex - 十六进制颜色
 * @param {Object} [opts]
 * @param {boolean} [opts.asString=false] - 返回 'rgba(r,g,b,a)' 字符串而非数组
 * @returns {number[]|string}
 */
export function hexToOlColor(hex, opts = {}) {
  if (!hex || typeof hex !== 'string') throw new Error('hex must be a string')
  hex = hex.replace(/^\s*#/, '').trim()

  // Expand short forms: RGB -> RRGGBB, RGBA -> RRGGBBAA
  if (hex.length === 3 || hex.length === 4) {
    hex = hex
      .split('')
      .map((ch) => ch + ch)
      .join('')
  }

  let r = 0,
    g = 0,
    b = 0,
    a = 255
  if (hex.length === 6) {
    r = parseInt(hex.slice(0, 2), 16)
    g = parseInt(hex.slice(2, 4), 16)
    b = parseInt(hex.slice(4, 6), 16)
  } else if (hex.length === 8) {
    r = parseInt(hex.slice(0, 2), 16)
    g = parseInt(hex.slice(2, 4), 16)
    b = parseInt(hex.slice(4, 6), 16)
    a = parseInt(hex.slice(6, 8), 16)
  } else {
    throw new Error('Invalid hex color length')
  }

  const alpha = +(a / 255).toFixed(3) // 0-1, 保留 3 位小数
  const arr = [r, g, b, alpha]

  return opts.asString ? `rgba(${r},${g},${b},${alpha})` : arr
}
